package com.polaris.live.common.util

import android.graphics.Rect
import android.view.ViewTreeObserver
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner

object SoftKeyBoardHelper {

    fun setListener(activity: AppCompatActivity, listener: OnSoftKeyboardChangeListener?) {
        if (activity.lifecycle.currentState == Lifecycle.State.DESTROYED) {
            return
        }

        val rootView = activity.window.decorView
        val wrapper = HeightWrapper()
        val listener = ViewTreeObserver.OnGlobalLayoutListener {
            val r = Rect()
            rootView.getWindowVisibleDisplayFrame(r)
            val height = r.height()
            if (wrapper.height == 0) {
                wrapper.height = height
            } else {
                val diff = wrapper.height - height
                if (diff > 200) {
                    listener?.keyBoardShow()
                    wrapper.height = height
                } else if (diff < -200) {
                    listener?.keyBoardHide()
                    wrapper.height = height
                }
            }
        }

        activity.lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    rootView.viewTreeObserver.removeOnGlobalLayoutListener(listener)
                }
            }
        })
        rootView.viewTreeObserver.addOnGlobalLayoutListener(listener)
    }

    interface OnSoftKeyboardChangeListener {

        fun keyBoardShow()
        fun keyBoardHide()
    }

    private class HeightWrapper {

        var height = 0
    }
}